package com.liujs.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liujs@centaline.com.cn
 * @description
 * @date 2020/10/13 15:54
 */
@Configuration
@Component
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.donguan-master")
    public DataSource donguanMasterDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.tianjin-master")
    public DataSource tianjinSlaveDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource donguanMasterDataSource, DataSource tianjinSlaveDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceNames.dg,donguanMasterDataSource);
        targetDataSources.put(DataSourceNames.tj, tianjinSlaveDataSource);
        return new DynamicDataSource(donguanMasterDataSource, targetDataSources);
    }
}
